﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace UpLoadDataOnTime.DataBaseUtil
{
    public static class SerializeData
    {
        internal static DataTable ToDataTable<T>(List<T> entities) /*where T : class,new()*/
        {



            // IsNull 

            if (entities == null || entities.Count == 0)

            {

                return null;

            }

            // 反射机制获取 传入的实体类型的全部公有属性
            PropertyInfo[] pArray = typeof(T).GetProperties();

            try
            {
                DataTable dt = new DataTable();

                // Insert Columns
                Array.ForEach(pArray, p =>
                {
                    dt.Columns.Add(p.Name);
                });

                // 遍历集合插入
                entities.ForEach(p =>
                {
                    // Insert Rows
                    DataRow row = dt.NewRow();
                    int i = 0;
                    Array.ForEach(pArray, m =>
                    {
                        if (dt.Columns.Contains(m.Name))
                        {
                            row[i] = m.GetValue(p);
                        }
                    });

                    i++;

                    dt.Rows.Add(row);
                });

                return dt;
            }

            catch (Exception)
            {
                throw;
            }
        }



        internal static List<T> ToEntities<T>(DataTable dt) where T : class, new()
        {
            // IsNull
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }

            List<T> entities = new List<T>();

            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    PropertyInfo[] pArray = typeof(T).GetProperties();
                    T entity = new T();

                    Array.ForEach(pArray, p =>
                    {

                        if (row[p.Name] != DBNull.Value)

                        p.SetValue(entity, row[p.Name], null);
                    });
                    entities.Add(entity);
                }
                return entities;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
